package tr.gov.tubitak.uekae.esya.api.xades.example.utils;

import org.w3c.dom.Document;

import com.xuxux.utils.commons.MyXmlUtil;

import tr.gov.tubitak.uekae.esya.api.asn.x509.ECertificate;
import tr.gov.tubitak.uekae.esya.api.common.ESYAException;
import tr.gov.tubitak.uekae.esya.api.xmlsignature.Context;
import tr.gov.tubitak.uekae.esya.api.xmlsignature.XMLSignatureException;
import tr.gov.tubitak.uekae.esya.api.xmlsignature.config.Config;
import tr.gov.tubitak.uekae.esya.api.xmlsignature.resolver.OfflineResolver;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;

/**
 * Represents a base for signature samples
 * @author suleyman.uslu
 */
public class SampleBase
{
    protected static String ROOT_DIR;           // root directory of project
    protected static String CONFIG;             // config file path
    protected static String BASE_DIR;           // base directory where signatures created
    protected static String POLICY_FILE;        // certificate validation policy file path
    protected static String POLICY_FILE_CRL;    // path of policy file without OCSP
    protected static String PFX_FILE;           // PFX path
    protected static String PFX_PASS;           // PFX password
    protected static String PIN;                // smartcard PIN

    protected static ECertificate CERTIFICATE;  // certificate of PFX
    protected static PrivateKey PRIVATE_KEY;    // private key of PFX

    protected static OfflineResolver POLICY_RESOLVER;   // policy resolver for profile examples

    public static final int[] OID_POLICY_P2 = new int[]{2,16,792,1,61,0,1,5070,3,1,1};
    public static final int[] OID_POLICY_P3 = new int[]{2,16,792,1,61,0,1,5070,3,2,1};
    public static final int[] OID_POLICY_P4 = new int[]{2,16,792,1,61,0,1,5070,3,3,1};

    private static final String ENVELOPE_XML =  // sample XML document used for enveloped signature
                    "<envelope>\n" +
                    "  <data id=\"data1\">\n" +
                    "    <item>Item 1</item>\n"+
                    "    <item>Item 2</item>\n"+
                    "    <item>Item 3</item>\n"+
                    "  </data>\n" +
                    "</envelope>\n";

    /**
     * Initialize paths and other variables
     */
    static {

        URL root = SampleBase.class.getResource("../../../../../../../../../");
        String classPath = root.getPath();
        File binDir = new File(classPath);

        //ROOT_DIR = binDir.getParent();
        ROOT_DIR = "D:/Workspaces/kepler/testsForSigner/MA3-JAVA API";
        BASE_DIR = ROOT_DIR + "/testdata/";
        CONFIG = ROOT_DIR + "/config/xmlsignature-config.xml";
        POLICY_FILE = ROOT_DIR + "/config/certval-policy-test.xml";
        POLICY_FILE_CRL = ROOT_DIR + "/config/certval-policy-test-crl.xml";
        PFX_FILE = ROOT_DIR + "/sertifika deposu/072801_test2.pfx";
        PFX_PASS = "072801";
        PIN = "975998";
//        PIN = "1242";

        System.out.println("Base dir : " + BASE_DIR);

        POLICY_RESOLVER = new OfflineResolver();
        POLICY_RESOLVER.register("urn:oid:2.16.792.1.61.0.1.5070.3.1.1", ROOT_DIR + "/config/profiller/Elektronik_Imza_Kullanim_Profilleri_Rehberi.pdf", "text/plain");
        POLICY_RESOLVER.register("urn:oid:2.16.792.1.61.0.1.5070.3.2.1", ROOT_DIR + "/config/profiller/Elektronik_Imza_Kullanim_Profilleri_Rehberi.pdf", "text/plain");
        POLICY_RESOLVER.register("urn:oid:2.16.792.1.61.0.1.5070.3.3.1", ROOT_DIR + "/config/profiller/Elektronik_Imza_Kullanim_Profilleri_Rehberi.pdf", "text/plain");

        try {

            KeyStore ks = KeyStore.getInstance("PKCS12");

            ks.load(new FileInputStream(PFX_FILE), PFX_PASS.toCharArray());

            String alias = ks.aliases().nextElement();
            PRIVATE_KEY = (PrivateKey)ks.getKey(alias, PFX_PASS.toCharArray());
            Certificate cert = ks.getCertificate(alias);
            CERTIFICATE = new ECertificate(cert.getEncoded());
        }
        catch (Exception x){
            x.printStackTrace();
        }
    }

    /**
     * Creates context for signature creation and validation
     * @return created context
     */
    public static Context createContext() {
    	
    	Context context = null;
    	try {
			context = new Context(BASE_DIR);
			context.setConfig(new Config(CONFIG));
		} catch (XMLSignatureException e) {
			e.printStackTrace();
		}
    	return context;
    }

    /**
     * Creates sample envelope XML that will contain signature inside
     * @return envelope in Document format
     * @throws tr.gov.tubitak.uekae.esya.api.common.ESYAException
     */
    public Document newEnvelope() throws ESYAException {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();

            return db.parse(new ByteArrayInputStream(ENVELOPE_XML.getBytes()));
        }
        catch (Exception x){
            // we shouldn't be here if ENVELOPE_XML is valid
            x.printStackTrace();
        }
        throw new ESYAException("Cant construct envelope xml ");
    }
    
    public Document newUnsignedUblInvoice() throws ESYAException {
        try {
            return MyXmlUtil.parse(new FileInputStream("C:/Users/xuxux/Desktop/unsignedUbl_Invoice.xml"));
        }
        catch (Exception x){
            // we shouldn't be here if ENVELOPE_XML is valid
            x.printStackTrace();
        }
        throw new ESYAException("Cant construct envelope xml ");
    }
    
}
